import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from blog.lib.base import BaseController, render
from blog.model import meta
from blog.meta import Session
from blog.model import Right
from blog.lib import helpers

log = logging.getLogger(__name__)

class RightsController(BaseController):

    def __before__(self):
        self.right_q=Session.query(Right)

    def index(self):
        request.params['capital']
        if capital :
            if capital='!' :
               q=self._q
            else :
                q=self.right_q.filter(right.name.like('%s%%' % capital))
            c.rights=helpers.pagenite.Page(q)
        else :
            c.rights=[]
        if 'particle' in request.params :
            return render('/right/index/particle.mako')
        else :
            return render('/right/index/full.mako')

    def show(self,rid):
        right=self.rigt_q.filter(right.id=rid).first()
        c.right=right
        return render('/right/show.mako')

    def make(self):
        return render('/right/make.mako')
    
    @authernticate_form
    def creat(self):
        name=request.params['name']
        read=request.params['read']
        write=request.params['write']
        reply=request.params['reply']
        create=request.params['create']
        secret=request.params['secret']
        manage=request.params['manage']
        right=Right(**locals())
        Session.add(right)
        Session.commit()
    
    def edit(self,rid):
        right=self.right_q.filter(right.id=rid).first()
        c.right=right
        return render('/right/edit.mako')

    @authernticate_form
    def modify(self):
        right=self.right_q.filter(right.id=rid).first()
        right.name=request.params['name']
        right.read=request.params['read']
        right.write=request.params['write']
        right.reply=request.params['reply']
        right.create=request.params['create']
        right.secret=request.params['secret']
        right.manage=request.params['manage']
        Session.add(right)
        Session.commit()
       
    def check(self):
        name=request.params.get('name')
        int_=request.params.get('int')
        if name:
            r=self.right_q.filter(right.name=name)
            if r:
                return 'False'
            else :
                return 'True'
        if int_:
            try :
                assert int(int_)<=32767;
            except (AssertionError,ValueError):
                return 'False';
            else :
                return 'True';
        return ''
    
